using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Zsnd.Helpers;
using MaymuseMS.DAL;
using MaymuseMS.Models;

namespace MaymuseMS.Controllers {
    public class OrderController : GenericController {

        public ActionResult Index() {
            return View();
        }

        [HttpPost]
        public ActionResult Index(JQGridParm parm) {
            string sidx = parm.Sidx;
            string sord = parm.Sord;
            int page = parm.Page;
            int rows = parm.Rows;

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = unitOfWork.OrderRepository.dbSet.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            var entities = unitOfWork.OrderRepository.Get(pageIndex, pageSize, sidx, sord, parm.Filters);

            var enums = entities.Select(e => new {
                id = e.OrderId,
                cell = new object[] { 
                    e.Number,
                    e.Date.ToDate(),
                    e.Supplier.Number,
                    e.Supplier.Contacts.Phone,
                    e.Supplier.Contacts.Fax,
                    e.SupplierUser.Name,
                    e.Total,
                    e.Remark
                }
            });

            var jsonData = new {
                success = true,
                total = totalPages,
                page,
                records = totalRecords,
                rows = enums
            };
            return Json2(jsonData);
        }

        [HttpPost]
        public ActionResult Add(Order order, int supplieruserid, string counts, string prices, string productitemids) {
            //Order orderAdd = new Order();

            //order.State = 1;
            if (order.Date == DateTime.Parse("0001-1-1")) order.Date = DateTime.Now;

            var supplierUser = unitOfWork.SupplierUserRepository.Get(supplieruserid);
            order.SupplierUser = supplierUser;
            order.Supplier = supplierUser.Supplier;
            //unitOfWork.OrderRepository.Add(order);
            //unitOfWork.Save();

            IList<double> countList = counts.ToDouList();
            IList<int> productItemIdList = productitemids.ToIntList();
            IList<decimal> priceList = prices.ToDecList();
            for (int i = 0; i < countList.Count; i++) {
                ProductItem productItem = unitOfWork.ProductItemRepository.Get(productItemIdList[i]);
                OrderItem orderItem = new OrderItem {
                    Count = countList[i], Price = priceList[i], Order = order,
                    ProductValueObject = new Models.ValueObject.ProductValueObject {
                        Model = productItem.Product.Model,
                        Name = productItem.Product.Name,
                        Number = productItem.Product.Number,
                        Spec = productItem.Product.Spec,
                        Unit = productItem.Product.Unit
                    }
                };

                unitOfWork.OrderItemRepository.Add(orderItem);

                order.OrderItems.Add(orderItem);
            }
            //if (TryUpdateModel(orderAdd)) {
            unitOfWork.OrderRepository.Add(order);
            unitOfWork.Save();
            return Json2(new { success = true });
            //}

            //return Json2(new { success = false, message = errorMessage });
        }

        [HttpPost]
        public ActionResult Edit(int? id, Order order) {
            if (id != null) {
                Order orderEdit = unitOfWork.OrderRepository.Get((int)id);
                if (orderEdit != null) {
                    if (TryUpdateModel(orderEdit)) {
                        unitOfWork.Save();
                        return Json2(new { success = true });
                    }
                }
            }
            return Json2(new { success = false, message = errorMessage });
        }

        [HttpPost]
        public ActionResult Delete(string id) {
            if (string.IsNullOrWhiteSpace(id))
                Json2(new { success = false, message = errorMessage });
            try {
                unitOfWork.OrderRepository.Remove(id);
                unitOfWork.Save();
                return Json2(new { success = true });
            } catch (ArgumentNullException e) {
                return Json2(new { success = false, message = e.Message });
            } catch (Exception e) {
                return Json2(new { success = false, message = errorMessage });
            }
        }

        public ActionResult Orders() {
            var orders = unitOfWork.OrderRepository.dbSet.Select(s => new { key = s.OrderId, value = s.Number }).AsEnumerable();
            var jsonData = new { value = orders };
            return Json2(jsonData);
        }

        //public ActionResult PurchasingOrders() {
        //    var orders = unitOfWork.OrderRepository.dbSet
        //        .Where(o => o.State == 1)
        //        .Select(s => new { key = s.OrderId, value = s.Number }).AsEnumerable();
        //    var jsonData = new { value = orders };
        //    return Json2(jsonData);
        //}

        //public ActionResult State() {
        //    var state = Order.OrderState.Select(s => new { key = s.Key, value = s.Value });
        //    var jsonData = new { value = state };
        //    return Json2(jsonData);
        //}

        public ActionResult GetOrder(int id) {
            var order = unitOfWork.OrderRepository.dbSet.Include("OrderItems").FirstOrDefault(o => o.OrderId == id);
            if (order == null)
                return Json2(new { success = false, message = errorMessage });

            var orderitems = order.OrderItems;
            var items = orderitems.Select(item => new object[] {
                item.ProductValueObject.Number,
                item.ProductValueObject.Name,
                item.ProductValueObject.Spec,
                item.Count,
                item.ProductValueObject.Unit,
                item.Price,
                (decimal)item.Count * item.Price
            });
            var jsonData = new {
                success = true,

                number = order.Number,
                supplier = order.Supplier.Name,
                address = order.Supplier.Contacts.Address,
                phone = order.Supplier.Contacts.Phone,
                fax = order.Supplier.Contacts.Fax,
                supplieruser = order.SupplierUser.Name,

                orderitems = items,

                date = order.Date.ToDate(),
                demand = order.Demand,
                daddress = order.Address,
                dphone = order.Phone,
                dfax = order.Fax,
                demanduser = order.DemandUser,

                total = order.Total,

                remark = order.Remark,
                productrequirements = order.ProductRequirements,
                packagingrequirements = order.PackagingRequirements,
                deliverydate = order.DeliveryDate.ToDate(),
                deliveryaddress = order.DeliveryAddress,
                consignee = order.Consignee,
                consigneetelphone = order.ConsigneeTelphone,
                other = order.Other
            };
            return Json2(jsonData);
        }
    }
}

